package weaver.jobs.cese;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.cese.duss.ceseutil.Json2XmlUtils;
import weaver.interfaces.cese.duss.ceseutil.OcrUitl;
import weaver.interfaces.schedule.BaseCronJob;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @Title: ecology
 * @Company: 泛微软件
 * @author: weaver.Dusongsong
 * @version: 1.0
 * @CreateDate: 2020-10-30
 * @Description: 定时发送发票影像文件到浪潮
 * @ModifyLog:
 **/

public class WeaImageUploadCronJob extends BaseCronJob {
    @Override
    public void execute() {
        Map<String, Object> params = new HashMap<>();
        BaseBean baseBean = new BaseBean();
        baseBean.writeLog("--------WeaImageUploadCronJob---------");
        String clientcode = "WB";//调用系统代码
        String servicecode = "ImageCenter";//提供服务的系统编码
        String currentDate = DateUtil.getCurrentDate();//当前时间
        String date = DateUtil.getFullDate().substring( 0, 10 ).replaceAll( "-", "" );
        String time = date + DateUtil.getFullDate().substring( 11, 19 ).replaceAll( ":", "" );//明文参数验证时，该节点必输，格式为：YYYYMMDDHHmmSS
        String img_API_KEY = baseBean.getPropValue("langchao","IMG_API_KEY");
        String img_url =  baseBean.getPropValue("langchao","img_url");
        String ticket = time + servicecode + clientcode + img_API_KEY;//明文参数验证时，该节点必输，取值为：time值+ servicecode 值+ clientcode 值+约定KEY，生成的MD5值
        String md5Ticket = DigestUtils.md5Hex( ticket );
        String servername = "sendImage";//调用的服务标记
        String servertype = "";//调用的服务类型，0/实时接口，1/定时接口，影像系统可配置，默认取影像系统配置
        params.put( "clientcode", clientcode );
        params.put( "servicecode", servicecode );
        params.put( "time", time );
        params.put( "ticket", md5Ticket );
        params.put( "servername", servername );
        params.put( "servertype", servertype );
        RecordSet rs = new RecordSet();
        String sql = "select fplrr,ssfrzz,hth,fpyx from uf_fpxx where lrrq=? and fplx in (7,9,13)";
        rs.executeQuery( sql, currentDate );
        int scount = 0;
        int fcount = 0;
        int count=0;
        while (rs.next()) {
            int counts = rs.getColCounts();
            String fplrr = Util.null2String( rs.getString( "fplrr" ) );//人员
            String ssfrzz = Util.null2String( rs.getString( "ssfrzz" ) );//部门
            String hth = Util.null2String( rs.getString( "hth" ) );//合同号
            int fpyx = Util.getIntValue( rs.getString( "fpyx" ) );//影像ID
            InputStream inputStream = OcrUitl.getInputStreamById( fpyx );
            try{
                String barcode = hth;//单据编码或者合同号
                String content = IOUtils.toString(inputStream, "utf-8");//图片或pdf序列化后的Base64值
                String filename = getDocid2Imagefile(fpyx);//文件名（包括扩展名称）
                String compoanycode = ssfrzz;//单位编号
                String useraccount = fplrr;//上传用户
                String page = count+"";//当前页数
                String totalpage = counts+"";//总记录
                params.put( "serviceid", count );
                params.put( "barcode", barcode );
                params.put( "filename", filename );
                params.put( "content", content );
                params.put( "compoanycode", compoanycode );
                params.put( "useraccount", useraccount );
                params.put( "page", page );
                params.put( "totalpage", totalpage );
                count++;
            }catch (Exception e){
               e.printStackTrace();
            }
            String param = XMLContent( params );
            String str = "param=" + param;
            Map<String, String> headers = new HashMap<>();
            headers.put( "Content-Type", "application/x-www-form-urlencoded" );
            String returns = OcrUitl.httpPostRaw( img_url, str, headers, "UTF-8" );
            if (returns.contains( "success" )) {
                baseBean.writeLog("当前COUNT=["+scount+"]-------success--------Docid："+fpyx );
                scount++;
            }else {
                baseBean.writeLog("当前COUNT=["+fcount+"]-------error--------Docid："+fpyx );
                fcount++;
            }
        }
        baseBean.writeLog("总数：["+count+"]--成功数：["+scount+"]--失败数：["+fcount+"]");
    }

    /**
     * 组装XML
     */
    public static String XMLContent(Map<String, Object> map) {
        String result = "";
        JSONObject xml = new JSONObject();
        JSONObject params = new JSONObject();
        JSONObject safety = new JSONObject();
        safety.put( "clientcode", map.get( "clientcode" ) );
        safety.put( "servicecode", map.get( "servicecode" ) );
        safety.put( "time", map.get( "time" ) );
        safety.put( "ticket", map.get( "ticket" ) );
        JSONObject serverbody = new JSONObject();
        serverbody.put( "servername", map.get( "servername" ) );
        serverbody.put( "servertype", map.get( "servertype" ) );
        JSONObject services = new JSONObject();
        JSONObject service = new JSONObject();
        service.put( "serviceid", map.get( "serviceid" ) );
        service.put( "barcode", map.get( "barcode" ) );
        service.put( "filename", map.get( "filename" ) );
        service.put( "content", map.get( "content" ) );
        service.put( "compoanycode", map.get( "compoanycode" ) );
        service.put( "useraccount", map.get( "useraccount" ) );
        service.put( "page", map.get( "page" ) );
        service.put( "totalpage", map.get( "totalpage" ) );
        services.put( "service", service );
        serverbody.put( "services", services );
        params.put( "safety", safety );
        params.put( "serverbody", serverbody );
        xml.put( "params", params );
        try {
            result = Json2XmlUtils.jsonToPrettyXml( xml );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    //获取文件名
    public static String getDocid2Imagefile(int docid){
        RecordSet rs = new RecordSet();
        String sql = " select imagefilename from imagefile where imagefileid = (select imagefileid from docimagefile where docid =?)";
        rs.executeQuery(sql,docid);
        rs.next();
        String imagefilename = Util.null2String(rs.getString("imagefilename"));//文件名
        return imagefilename;
    }
    public static byte[] getContent(String path){
        byte[] content = new byte[102400];
        // 上传附件，创建html文档
        content = null;
        try {
            int byteread;
            byte data[] = new byte[1024];
            InputStream input = new FileInputStream(new File(path));
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            while ((byteread = input.read(data)) != -1) {
                out.write(data, 0, byteread);
                out.flush();
            }
            content = out.toByteArray();
            input.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }
}
